/*
	This file is part of Floculate.
	Copyright (C) 2008  Bill Whitacre

	Floculate is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Floculate is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "keymap.h"

rat_key_pair rat_key_pair_create(RAT_SYS_KEY syskey,RAT_KEY_CODE rekey)
{
    rat_key_pair kp={rekey,syskey};
    return kp;
}

rat_key_map *rat_key_map_create()
{
    rat_key_map *keymap;

    keymap=(rat_key_map *)malloc(sizeof(rat_key_map));

    keymap->numpairs=0;
    keymap->keypairs=NULL;

    return keymap;
}

void rat_key_map_destroy(rat_key_map *keymap)
{
    if (keymap->keypairs!=NULL)
        free(keymap->keypairs);
	free(keymap);
}

void rat_key_map_add_pair(rat_key_map *keymap,rat_key_pair keypair)
{
    rat_key_pair *tempbuf;

    if (keymap->keypairs)
    {
        keymap->numpairs++;
        tempbuf=realloc(keymap->keypairs,sizeof(rat_key_pair)*keymap->numpairs);
        keymap->keypairs=tempbuf;
    }
    else
    {
        keymap->numpairs++;
        keymap->keypairs=malloc(sizeof(rat_key_pair));
    }

    keymap->keypairs[keymap->numpairs-1]=keypair;
}

RAT_KEY_CODE rat_key_map_get_code(rat_key_map *keymap,RAT_SYS_KEY syskey)
{
    register int i;

    if (!keymap->keypairs) return 0;
    if (keymap->numpairs==0) return 0;

    for (i=0; i<keymap->numpairs; ++i)
    {
        if (keymap->keypairs[i].syskey==syskey) return keymap->keypairs[i].rekey;
    }

    return 0;
}

int kpcompare(const void *v0,const void *v1)
{
    const rat_key_pair *k0,*k1;

    k0=(rat_key_pair *)v0;
    k1=(rat_key_pair *)v1;

    if(k0->syskey<k1->syskey)
        return -1;
    else if(k0->syskey==k1->syskey)
        return 0;
    else
        return 1;
}

void rat_key_map_sort(rat_key_map *keymap)
{
    qsort(keymap->keypairs,keymap->numpairs,sizeof(rat_key_pair),kpcompare);
}
